import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Table, Tag, Space, Card, Button, Popconfirm, message } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import Search from './Search'
import img404 from '@/assets/error.png'
import { http } from '@/utils'


function Article() {
  // 请求参数
  const [params, setParams] = useState({
    page: 1,
    size: 10
  })
  // 文章列表管理
  const [articleList, setArticleList] = useState([])
  // 副作用请求列表数据
  useEffect(() => {
    (async function() {
      const { data } = await http.get('/api/article/list', params)
      if (data) {
        setArticleList(data)
      }
    })()
  }, [params])

  // 筛选回调
  const onSearch = _params => setParams({ ...params, ..._params })

  // 分页修改
  const pageChange = page => setParams({ ...params, page })

  // 删除文章
  const delArticle = async article => {
    const { data } = await http.delete(`/api/article/remove?id=${article.id}`)
      if (data) {
        message.success('删除成功')
      }
  }
  // 编辑文章
  const navigate = useNavigate()
  const onEdit = article => {
    navigate(`/publish?id=${article.id}`)
  }

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width: 120,
      render: cover => {
        return <img src={cover.images || img404} width={80} height={60} alt="" />
      }
    },
    { title: '标题', dataIndex: 'title', width: 200 },
    { title: '状态', dataIndex: 'status', render: data => <Tag color="green">审核通过</Tag>},
    { title: '发布事件', dataIndex: 'pubdate'},
    { title: '阅读量', dataIndex: 'read_count'},
    { title: '评论数', dataIndex: 'comment_count'},
    { title: '点赞数', dataIndex: 'like_count'},
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => onEdit(data)}
            />
            <Popconfirm
              title="确认删除该条文章吗?"
              onConfirm={() => delArticle(data)}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  return (
    <div>
      <Search search={onSearch} />
      <Card title={`根据筛选条件共查询到 ${articleList.length} 条结果：`}>
        <Table
          rowKey='id'
          columns={columns}
          dataSource={articleList}
          pagination={{
            position: ['bottomRight'],
            current: params.page,
            pageSize: params.size,
            onChange: pageChange
          }}
        />
      </Card>
    </div>
  )
}

export default Article